package com.zwp.base.binding

import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.ShapeDrawable
import android.graphics.drawable.shapes.RoundRectShape
import android.graphics.drawable.shapes.Shape
import android.view.View
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.databinding.BindingAdapter
import androidx.lifecycle.findViewTreeLifecycleOwner
import androidx.lifecycle.lifecycleScope
import com.google.android.material.shape.MaterialShapeDrawable
import com.google.android.material.shape.RoundedCornerTreatment
import com.google.android.material.shape.ShapeAppearanceModel
import com.zwp.base.R
import com.zwp.base.ext.clickFlow
import com.zwp.base.ext.longClickFlow
import com.zwp.base.ext.throttleFirst
import kotlinx.coroutines.flow.*


@BindingAdapter(value = ["onClickCommand", "isThrottleFirst"], requireAll = false)
fun onClickCommand(
    view: View,
    clickCommand: BindingCommand<BindingAction>?,
    isThrottleFirst: Boolean
) {
    view.findViewTreeLifecycleOwner()?.lifecycleScope?.let {
        view.clickFlow()
            .throttleFirst(200)
            .onEach {
                clickCommand?.execute()
            }.launchIn(it)
    }
}

@BindingAdapter(value = ["onLongClickCommand"])
fun onLongClickCommand(view: View, longClickCommand: BindingCommand<BindingAction>?) {
    view.findViewTreeLifecycleOwner()?.lifecycleScope?.let {
        view.longClickFlow()
            .throttleFirst(1000)
            .onEach {
                longClickCommand?.execute()
            }.launchIn(it)
    }
}

@BindingAdapter(value = ["onFocusChangeCommand"])
fun onFocusChangeCommand(view: View, onFocusChangeCommand: BindingCommand<Boolean>?) {
    view.setOnFocusChangeListener { _, hasFocus ->
        onFocusChangeCommand?.execute(hasFocus)
    }
}

@BindingAdapter(value = ["isVisible"])
fun isVisible(view: View, visibility: Boolean) {
    view.isVisible = visibility
}


